package com.cuitrip.business.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.business.login.proxy.VcodeProxy;
import com.cuitrip.service.R;
import com.lab.app.BaseActivity;
import com.lab.logtrack.AppLog;
import com.lab.utils.MessageUtils;
import com.lab.utils.SmsSdkHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.ButterKnife;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.CountryPage;

public abstract class VcodeActivity extends BaseActivity implements
        Handler.Callback, CountryPage.OnResult {

    private static final int UPDATE_TIME = 1;
    private static final int DURATION = 30;


    private HashMap<String, String> countryRules;

    private Handler mHandler;

    private String currentId;
    private String currentCode;

    private Animation mShakeAnimation;

    public String getCurrentCode() {
        return currentCode;
    }

    public String getCurrentId() {
        return currentId;
    }

    protected abstract int getLayoutRes();

    protected abstract TextView getVcodeView();

    protected abstract EditText getPhoneNum();

    protected abstract View phoneNumClearView();

    protected abstract TextView getCountryView();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutRes());
        ButterKnife.bind(this);
        SmsSdkHelper.registerEventHandler(mEventHandler);
        mHandler = new Handler(this);
        initData();
        initListener();
        mShakeAnimation = AnimationUtils.loadAnimation(this, R.anim.shake);
    }

    private void initData() {
        String countryCode = VcodeProxy.getInstance().getCurrentCountryCode(this);
        if (!TextUtils.isEmpty(countryCode)) {
            setCurrentCode(countryCode);
        }
    }

    private void initListener() {
        getCountryView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CountryPage countryPage = new CountryPage();
                countryPage.setCountryId(currentId);
                countryPage.setCountryRuls(countryRules);
                countryPage.setOnResultListener(VcodeActivity.this);
                countryPage.showForResult(VcodeActivity.this, null);
            }
        });
        getVcodeView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getPhoneNum().getText().toString().trim())) {
                    getPhoneNum().startAnimation(mShakeAnimation);
                    return;
                }
                if (TextUtils.isEmpty(currentCode)) {
                    getCountryView().startAnimation(mShakeAnimation);
                    return;
                }
                SmsSdkHelper.getVerificationCode(currentCode, getPhoneNum().getText().toString().trim());
//                getVcodeView().setText(R.string.verification_code_second);
                getVcodeView().setClickable(false);
                getVcodeView().setEnabled(false);
            }
        });
        getPhoneNum().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onAccountChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        phoneNumClearView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhoneNum().setText("");
            }
        });
    }


    public void setCurrentCode(String currentCode) {
        this.currentCode = currentCode;
        if (currentCode != null && currentCode.equals("886")) {
            if (TextUtils.isEmpty(getPhoneNum().getText().toString().trim())) {
                getPhoneNum().setSelection(getPhoneNum().getText().toString().length());
            }
        }
        getCountryView().setText("+" + currentCode);
    }

    public void onAccountChanged() {
        phoneNumClearView().setVisibility(TextUtils.isEmpty(getPhoneNum().getText().toString()) ? View.INVISIBLE : View.VISIBLE);
    }


    protected void onDestroy() {
        super.onDestroy();
        SmsSdkHelper.unregisterEventHandler(mEventHandler);
    }


    /**
     * 检查电话号码
     */
    private void checkPhoneNum(String phone, String code) {
        if (code.startsWith("+")) {
            code = code.substring(1);
        }

        if (TextUtils.isEmpty(phone)) {
            //MessageUtils.showToast(R.string.ct_null_phone);
            return;
        }

        String rule = countryRules.get(code);
        Pattern p = Pattern.compile(rule);
        Matcher m = p.matcher(phone);
        if (!m.matches()) {
//            MessageUtils.showToast(R.string.ct_error_phone);
            return;
        }
    }

    EventHandler mEventHandler = new EventHandler() {

        @Override
        public void afterEvent(int event, int result, Object data) {

            if (result == SMSSDK.RESULT_COMPLETE) {
                AppLog.d("afterEvent success");
                //回调完成
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(UPDATE_TIME, DURATION), 1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
//                            getVcodeView().setText(getString(R.string.verification_code_resend_second,DURATION));
                            getVcodeView().setClickable(false);
                            getVcodeView().setEnabled(false);
                        }
                    });
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                    onCountryListGot((ArrayList<HashMap<String, Object>>) data);
                }
            } else {
                AppLog.d("afterEvent error");
                try {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            getVcodeView().setText(getText(R.string.operation_send));
                            getVcodeView().setClickable(true);
                            getVcodeView().setEnabled(true);
                        }
                    });
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;

                    JSONObject object = new JSONObject(
                            throwable.getMessage());
                    final String des = object.optString("detail");
                    if (!TextUtils.isEmpty(des)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                MessageUtils.showToast(des);
                            }
                        });
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MessageUtils.showToast(R.string.verification_code_send_feedback_fail);
                    }
                });
            }
        }

        public void onRegister() {
            AppLog.d("onRegister success");
        }

        public void beforeEvent(int var1, Object var2) {
        }

        public void onUnregister() {
            AppLog.d("onUnregister success");
        }
    };

    private void onCountryListGot(ArrayList<HashMap<String, Object>> countries) {
        // 解析国家列表
        for (HashMap<String, Object> country : countries) {
            String code = (String) country.get("zone");
            String rule = (String) country.get("rule");
            if (TextUtils.isEmpty(code) || TextUtils.isEmpty(rule)) {
                continue;
            }

            if (countryRules == null) {
                countryRules = new HashMap<String, String>();
            }
            countryRules.put(code, rule);
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case UPDATE_TIME:
                try {
                    int time = (Integer) message.obj;
                    if (time > 0) {
//                        getVcodeView().setText(getString(R.string.verification_code_resend_second,time));
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(UPDATE_TIME, --time), 1000);
                    } else {
                        getVcodeView().setText(getText(R.string.operation_resend));
                        getVcodeView().setClickable(true);
                        getVcodeView().setEnabled(true);
                    }
                } catch (Exception e) {
                    getVcodeView().setText(getText(R.string.operation_send));
                    getVcodeView().setClickable(true);
                }
                return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CompleteUserInfoActivity.REQUEST_COMPLETE_USER) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    public void onResult(HashMap<String, Object> data) {
        if (data != null) {
            int page = (Integer) data.get("page");
            if (page == 1) {
                // 国家列表返回
                currentId = (String) data.get("id");
                countryRules = (HashMap<String, String>) data.get("rules");
                String[] country = SMSSDK.getCountry(currentId);
                if (country!=null&&country.length>=2) {
                    currentCode = country[1];
                    setCurrentCode(currentCode);
                }
                checkPhoneNum(getPhoneNum().getText().toString().trim(), currentCode);
            }
        }
    }
}
